import type { UserInfo } from '@/api/common';

import { defineStore } from 'pinia';
import { ref } from 'vue';
import { CommonApi } from '@/api/common';
import { LOGIN_TYPE } from '@/enums/login.enums';
import { IS_DEV } from '@/utils';
import { getAccessToken, getRefreshToken, removeToken, setToken } from '@/utils/auth.utils';
import { strIsEmpty } from '@/utils/is.utils';

export const useUserStore = defineStore('user', () => {
  const authStore = ref({
    accessToken: '',
    refreshToken: '',
    logType: undefined as number | undefined
  });

  const setAuthStore = (accessToken: string, refreshToken: string, logType?: number) => {
    authStore.value.accessToken = accessToken;
    authStore.value.refreshToken = refreshToken;
    authStore.value.logType = logType;
    if (IS_DEV) {
      // 生产环境注释
      setToken(accessToken, refreshToken);
    }
  };

  const getAuthStore = () => {
    return authStore.value;
  };

  const checkAuth = () => {
    return !strIsEmpty(authStore.value.accessToken);
  };

  const userInfo = ref<UserInfo>({} as UserInfo);

  const handleLogout = () => {
    return CommonApi.onAuthLogout(authStore.value.logType || LOGIN_TYPE.ID_CARD).finally(() => {
      resetAuth();
    });
  };

  // 获取用户信息
  const getUserInfo = () => {
    return CommonApi.getPatientInfo().then(res => {
      userInfo.value = res;
      return res;
    });
  };

  const resetAuth = () => {
    authStore.value.accessToken = '';
    authStore.value.refreshToken = '';
    userInfo.value = {} as UserInfo;
    uni.reLaunch({
      url: '/pages/index/index'
    });
    if (IS_DEV) {
      removeToken();
    }
  };

  if (IS_DEV) {
    // 生产环境注释
    authStore.value.accessToken = getAccessToken();
    authStore.value.refreshToken = getRefreshToken();
    if (authStore.value.accessToken) {
      setTimeout(() => {
        getUserInfo();
      }, 0);
    }
  }

  return {
    userInfo,
    handleLogout,
    getUserInfo,
    resetAuth,

    checkAuth,

    authStore,
    setAuthStore,
    getAuthStore
  };
});
